import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store/index'

import layoutIndex from '@/views/layout'
// 二级路由
import homeIndex from '@/views/layout/home'
import classifyIndex from '@/views/layout/classify'
import cartIndex from '@/views/layout/cart'
import userIndex from '@/views/layout/user'

const loginIndex = () => import('@/views/login')
const myorderIndex = () => import('@/views/myorder')
const payIndex = () => import('@/views/pay')
const paydetailIndex = () => import('@/views/paydetail')
const searchIndex = () => import('@/views/search/index.vue')
const searchList = () => import('@/views/search/list.vue')
Vue.use(VueRouter)

const routes = [
  { path: '/login', component: loginIndex },
  { path: '/myorder', component: myorderIndex },
  { path: '/pay', component: payIndex },
  // 动态路由传参，确认将来是哪个商品，路由参数中携带 id
  { path: '/paydetail/:id?', component: paydetailIndex },
  { path: '/search', component: searchIndex },
  { path: '/searchlist', component: searchList },
  {
    path: '/',
    component: layoutIndex,
    redirect: '/home',
    children: [
      { path: '/home', component: homeIndex },
      { path: '/classify', component: classifyIndex },
      { path: '/cart', component: cartIndex },
      { path: '/user', component: userIndex }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 导航前置守卫
const authUrls = ['/pay', '/myorder']
router.beforeEach((to, from, next) => {
  if (!authUrls.includes(to.path)) {
    next()
    return
  }
  // 是权限页面
  const token = store.state.user.userInfo.token
  if (token) {
    next()
  } else {
    next('/login')
  }
})
export default router
